package com.njlime.sys.controller.app;

import com.njlime.cms.service.app.AppChannelService;
import com.njlime.core.base.controller.BaseAppController;
import com.njlime.core.utils.StringUtil;
import com.njlime.core.web.AppWxInterceptor;
import com.njlime.sys.security.util.CacheUtils;
import com.njlime.sys.security.util.UserUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 前台页面统一跳转控制器
 * Created by Dean on 2017-9-18.
 */
@Controller
@RequestMapping(value = "app")
public class AppController extends BaseAppController {

    @Resource
    private AppChannelService appChannelService;

    /**
     * /app/page?xx=xx格式的跳转
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/page")
    public ModelAndView page(HttpServletRequest request, HttpServletResponse response, Integer unit_id) {
        ModelAndView modelAndView = new ModelAndView("/app/index");
        try{
            if(unit_id == null){
                unit_id = (Integer)request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
            }
            //存储单位信息
            Integer root_unit_id = unitService.getRootUnit(unit_id);
            request.getSession().setAttribute(AppWxInterceptor.WX_USER_UNIT_ID, unit_id);
            request.getSession().setAttribute(AppWxInterceptor.WX_USER_ROOT_UNIT_ID, root_unit_id);
            for (Map.Entry<String, String[]> param : request.getParameterMap().entrySet()) {
                String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : "");
                modelAndView.addObject(param.getKey(), paramValue);
            }
            //获取频道列表
            modelAndView.addObject("channelList",appChannelService.getChannelList(root_unit_id));
            //微信tbs浏览器处理
            modelAndView = wxTbsCache(request, modelAndView);
        }catch (Exception e){
            modelAndView.addObject("msg", "页面找不到了，联系下管理员吧~");
            modelAndView.setViewName("/app/subscribe");
        }
        return modelAndView;
    }

    /**
     * /app/page/{pv}?xx=xx格式的跳转
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/page/{pv}")
    public ModelAndView page(@PathVariable(value = "pv") String pv, HttpServletRequest request, HttpServletResponse response, Integer unit_id) {
        if(unit_id == null){
            unit_id = (Integer)request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
        }
        ModelAndView modelAndView = new ModelAndView("/app/index");
        modelAndView.addObject("pv", pv);
        try {
            for (Map.Entry<String, String[]> param : request.getParameterMap().entrySet()) {
                String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : "");
                modelAndView.addObject(param.getKey(), paramValue);
            }
            //存储单位信息
            Integer root_unit_id = unitService.getRootUnit(unit_id);
            request.getSession().setAttribute(AppWxInterceptor.WX_USER_UNIT_ID, unit_id);
            request.getSession().setAttribute(AppWxInterceptor.WX_USER_ROOT_UNIT_ID, root_unit_id);
            //获取频道列表
            modelAndView.addObject("channelList",appChannelService.getChannelList(root_unit_id));
        }catch (Exception e){
            modelAndView.addObject("msg", "页面找不到了，联系下管理员吧~");
            modelAndView.setViewName("/app/subscribe");
        }
        return modelAndView;
    }

    private ModelAndView wxTbsCache(HttpServletRequest request, ModelAndView modelAndView){
        String agent = request.getHeader("user-agent");
        if(agent.contains("TBS/") && agent.contains("MicroMessenger/")){
            logger.info("微信TBS浏览器处理");
            Map<String,?> map = RequestContextUtils.getInputFlashMap(request);
            if(map != null) {
                System.out.println("input:" + map);
                CacheUtils.put(UserUtils.USER_CACHE, request.getParameter("token"), map);
            }else {
                logger.info("token:" + request.getParameter("token"));
                if(!StringUtil.isEmpty(request.getParameter("token"))){
                    map = (Map<String,?>) CacheUtils.get(UserUtils.USER_CACHE, request.getParameter("token"));
                    System.out.println("output:" + map);
                    if(map != null){
                        for (String key : map.keySet()) {
                            modelAndView.addObject(key, map.get(key));
                        }
                    }
                }
            }
        }
        return modelAndView;
    }

    @RequestMapping(value = "/tbsUse")
    @ResponseBody
    public String tbsUse(HttpServletRequest request, String token) {
        logger.info("微信TBS浏览器Cache清除");
        if(!StringUtil.isEmpty(token)) {
            CacheUtils.remove(UserUtils.USER_CACHE, token);
        }
        return toJsonSuccessData();
    }

}
